﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectFitus.Models;
using System.Web.Security;


namespace ProjectFitus.Controllers
{
	[HandleError]
	public class UserController : Controller
    {
		//IDBFitusNewsRepository m_repo;
		IDBFitusRepository m_repo;

		
		//default smiður fyrir db
		public UserController()
		{
			m_repo = new DBFitusRepository();
		}

		//smiður fyrir testing
		public UserController(IDBFitusRepository repo)
		{
			m_repo = repo;
		}

		protected override void OnException(ExceptionContext fc)
		{
			base.OnException(fc);
			FitusLogger.Instance.LogException(fc.Exception);		
		}

        //
        // GET: /User/
        public ActionResult Index()
        {
            
            return View();
        }

		[Authorize(Roles = "Administrators")]
		public ActionResult AdminManage()
		{
			return View();
		}

		[HttpPost]
		[Authorize(Roles = "Administrators")]
		public ActionResult WSAddUserToRole(string strUser, string strRole)
		{
			try
			{
				Roles.AddUserToRole(strUser, strRole);
				return Json("true");
			}
			catch 
			{ 
				return Json("false");
			}
		}


		[HttpPost]
		[Authorize(Roles = "Administrators")]
		public ActionResult WSRemoveUserFromRole(string strUser, string strRole)
		{
			try
			{
				Roles.RemoveUserFromRole(strUser, strRole);
				return Json("true");
			}
			catch 
			{
				return Json("false");
			}
		}

		[HttpGet]
		[Authorize(Roles = "Administrators")]
		public ActionResult WSGetAllRoles()
		{
			var roles = from r in Roles.GetAllRoles()
						select new { strRole = r};
			return Json(roles, JsonRequestBehavior.AllowGet);
		}

		[HttpGet]
		[Authorize(Roles = "Administrators")]
		public ActionResult WSGetUsersInRole(string strRole)
		{
			var strUserList = from u in Roles.GetUsersInRole(strRole)
						select new { strUser = u, strRoleName = strRole};
			return Json(strUserList, JsonRequestBehavior.AllowGet);
		}

		[HttpGet]
		[Authorize(Roles = "Administrators")]
		public ActionResult WSGetUsers()
		{
			List<string> strUserNames = new List<string>();
			foreach (MembershipUser u in Membership.GetAllUsers())
				strUserNames.Add(u.UserName);

			var test = from usr in strUserNames
					   select new { strUser = usr };

			return Json(test, JsonRequestBehavior.AllowGet);
		}
		
		
		//
        // GET: /User/Details/5

        public ActionResult Details(long? id)
        {
			UserAndSpecialistCapsule model = new UserAndSpecialistCapsule();
			if (!id.HasValue && Request.IsAuthenticated)
			{
				System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
				id = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
			}

			if (id.HasValue)
			{
				model.usr = m_repo.GetUserById(id.Value);
				model.speciali = m_repo.GetSpecialistById(id.Value);
				return View(model);
			}

			return RedirectToAction("Index", "Home");		
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        [HttpGet]
		[Authorize]
        public ActionResult Edit(int id)
        {
			var currentUsr = Membership.GetUser();
			if (currentUsr.UserName == m_repo.GetUserById(id).userName || User.IsInRole("Administrators"))
			{
				UserAndSpecialistCapsule model = new UserAndSpecialistCapsule();
				model.usr = m_repo.GetUserById(id);
				model.speciali = m_repo.GetSpecialistById(id);
				return View(model);
			}
			return View("Index");
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection formData)//(UserAndSpecialistCapsule returnable)
        {
            try
            {
                UserAndSpecialistCapsule returnable = new UserAndSpecialistCapsule();
                //Þarf tryParse hér?
                returnable.usr = m_repo.GetUserById(long.Parse(formData["id"]));
                returnable.speciali = m_repo.GetSpecialistById(long.Parse(formData["id"]));
                returnable.insertFromFormCollection(formData);
                //if (formData.AllKeys.Contains("firstName")
                //usr.isActive
                m_repo.UpdateUser(returnable.usr);
                if (returnable.speciali != null)
                {
                    m_repo.UpdateSpecialist(returnable.speciali);
                }
                //if (formData.AllKeys.Contains("firstName")
                // TODO: Add update logic here
                return RedirectToAction("Details/" + returnable.usr.id,"User");
            }
            catch
            {
                return View();
            }
        }
     
        //
        // GET: /User/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /User/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult UserProfile(long? userId)
        {
			if(!userId.HasValue)
			{
				System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
				return RedirectToAction("Details", new { id = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey) });
			}
			return View("Details", new { id = userId.Value });
        }
    }
}
